package cn.fl.mcr.service.impl;

import cn.cmm.base.framework.constant.BaseExceptionConstant;
import cn.fl.mcr.vo.McrVisitVO;
import cn.lionbridgecapital.loan.model.base.Pager;
import cn.lionbridgecapital.loan.model.condition.*;
import cn.lionbridgecapital.loan.model.dto.*;
import cn.lionbridgecapital.loan.service.api.*;
import com.alibaba.dubbo.config.annotation.Reference;
import fl.customer.facade.customer.api.ICustomerApiService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cmm.comm.facade.framework.api.ISysDictionaryApiService;
import cmm.mid.core.framework.dto.DataResultDTO;
import cmm.user.facade.system.api.ISysUsrQueryApiService;
import cmm.user.facade.system.condition.SysUsrSysRQueryCondition;
import cn.cmm.base.framework.constant.BaseConstant;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.base.framework.utils.BaseLogUtils;
import cn.cmm.base.framework.utils.CollectionUtils;
import cn.cmm.base.framework.utils.StringUtils;
import cn.cmm.cache.framework.utils.PropertiesCacheUtils;
import cn.fl.audit.service.IAudReturnVisitService;
import cn.fl.audit.vo.AudReturnVisitVO;
import cn.fl.framework.base.context.CurrentThreadContext;
import cn.fl.mcr.constant.McrCstCreditRecConstant;
import cn.fl.mcr.service.IMcrCstCreditRecService;
import cn.fl.mcr.transform.McrCstCreditRecVOTransform;
import cn.fl.mcr.vo.McrCstCreditRecVO;
import cn.fl.system.transform.SysUsrSysRVOTransform;
import cn.fl.system.vo.SysUsrSysRVO;
import com.alibaba.fastjson.JSONObject;
import fl.constant.facade.framework.constant.SystemConstant;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @Description: 客户小贷授信记录 客户端服务层接口实现
 * @Description: 业务层方法名称前缀：新增：add* 删除：remove* 修改：modify* 查询对象：select* get* 批量：batch* 查询集合：search*
 */
@Service
public class McrCstCreditRecServiceImpl implements IMcrCstCreditRecService {

	/**
	 * 日志
	 */
	private static final Logger logger = LoggerFactory.getLogger(IMcrCstCreditRecService.class);
	
	/**
	 * TODO 自定义 API 暴露服务
	 */
	@Autowired
	private IMcrCstCreditRecApiService publicMcrCstCreditRecApiService;
	
	@Autowired
	private IMcrCstCreditBlApiService mcrCstCreditBlApiService;

	@Autowired
	private IAudReturnVisitService audReturnVisitService;
	
	@Autowired
	private ISysUsrQueryApiService sysUsrQueryApiService;
	
	@Autowired
	private ISysDictionaryApiService sysDictionaryApiService;

	@Autowired
	private IMcrCstCrLimApiService publicMcrCstCrLimApiService;

	@Autowired
	private IMcrCstCrLimDtlApiService mcrCstCrLimDtlApiService;

	@Autowired
	private ICustomerApiService customerApiService;

	@Autowired
	private IMcrOutLoanApiService mcrOutLoanApiService;

	@Autowired
	private IMcrCstCrLimSchApiService publicMcrCstCrLimSchApiService;

	@Autowired
	private IMcrOutCommApiService mcrOutCommApiService;


	/*@Autowired
	private IInsVehicleLicenseApiService insVehicleLicenseApiService;*/
	
	@Override
	public McrCstCreditRecVO selectById(Long id) throws BaseException{
		if(StringUtils.isEmpty(id)){
			BaseLogUtils.info(logger, "selectById", "主键参数不能为空!", CurrentThreadContext.getCurrentUserName());
			return null;
		}
		McrCstCreditRecDTO dto = this.publicMcrCstCreditRecApiService.selectMcrCstCreditRecDTOById(id);
		return McrCstCreditRecVOTransform.toVO(dto);
	}

	@Override
	public Long add(McrCstCreditRecVO entity) throws BaseException{
		if(null == entity){
			BaseLogUtils.info(logger, "add", "新增对象不能为空!", CurrentThreadContext.getCurrentUserName());
			return null;
		}
		return publicMcrCstCreditRecApiService.addMcrCstCreditRec(McrCstCreditRecVOTransform.toDTO(entity));
	}

	@Override
	public boolean removeById(Long id) throws BaseException{
		if(StringUtils.isEmpty(id)){
			BaseLogUtils.info(logger, "removeById", "删除主键参数不能为空!", CurrentThreadContext.getCurrentUserName());
			return false;
		}
		return this.publicMcrCstCreditRecApiService.removeById(id);
	}
	
	/**
     * 删除
     * @param ids
     * @return
     */
    public boolean removeByIds(List<Long> ids)throws BaseException{
    	if(CollectionUtils.isEmpty(ids)){
    		BaseLogUtils.info(logger, "removeByIds", "删除主键参数集合不能为空!", CurrentThreadContext.getCurrentUserName());
			return false;
		};
		return false;
    }

	@Override
	public boolean modify(McrCstCreditRecVO entity) throws BaseException{
		if(null == entity){
			BaseLogUtils.info(logger, "modify", "修改对象参数不能为空!", CurrentThreadContext.getCurrentUserName());
			return false;
		}
		return publicMcrCstCreditRecApiService.modifyMcrCstCreditRecDTO(McrCstCreditRecVOTransform.toDTO(entity));
	}

	@Override
	public Pager searchListPage(Pager page) throws BaseException{
		if(null == page)page = new Pager();
		// List<McrCstCreditRecVO> list = McrCstCreditRecVOTransform.toVOList((List<McrCstCreditRecDTO>)mcrCstCreditRecApiService.searchMcrCstCreditRecListPage(page).getResultList());
		Pager resultPage = publicMcrCstCreditRecApiService.searchMcrCstCreditRecListPage(page);
		List<McrCstCreditRecDTO> dtoList = (List<McrCstCreditRecDTO>) resultPage.getResultList();
		List<McrCstCreditRecVO> voList = McrCstCreditRecVOTransform.toVOList(dtoList);
		Map<String, String> crTypCdMap = this.sysDictionaryApiService.searchGroupToMap(CurrentThreadContext.getCurrentSysCd(), CurrentThreadContext.getCurrentOrgCd(), McrCstCreditRecConstant.VISIT_STATUS);
		for (McrCstCreditRecVO vo : voList) {
			//获取信审回访信息
			AudReturnVisitVO visitVO = audReturnVisitService.selectByProjectId(vo.getId());
			if(visitVO != null){
				vo.setVisitCrtTm(visitVO.getCrtTm());
				vo.setAuditorName(visitVO.getAuditorName());
				if (crTypCdMap != null && crTypCdMap.containsKey(visitVO.getVisitStatus())) {
		            vo.setVisStatus(crTypCdMap.get(visitVO.getVisitStatus()));
		        }
			}

			// 兼容新数据-获取信审回访信息
			McrVisitProposerQC mcrVisitProposerQC = new McrVisitProposerQC();
			mcrVisitProposerQC.setProjectId(vo.getId());
			mcrVisitProposerQC.setIsDel(BaseConstant.IS_YESNO_NO);
			List<McrVisitProposerDTO> visitProposerDTOList = this.mcrOutLoanApiService.getVisitProposer(mcrVisitProposerQC);
			if (CollectionUtils.isNotEmpty(visitProposerDTOList)){
				McrVisitProposerDTO mcrVisitProposerDTO = visitProposerDTOList.get(0);
				vo.setVisitCrtTm(mcrVisitProposerDTO.getVisitDate());
				vo.setAuditorName(mcrVisitProposerDTO.getAuditorName());
				if (crTypCdMap != null && crTypCdMap.containsKey(visitVO.getVisitStatus())) {
					vo.setVisStatus(crTypCdMap.get(visitVO.getVisitStatus()));
				}
			}

			//获取用户信息
			SysUsrSysRQueryCondition condition = new SysUsrSysRQueryCondition();
			condition.setUsrId(vo.getUsrId());
			condition.setSysCd(PropertiesCacheUtils.getProperty(SystemConstant.FL_SERVICE_CD));
			condition.setIsDel(BaseConstant.IS_YESNO_NO);
			List<SysUsrSysRVO> usrList = SysUsrSysRVOTransform.toVOList(sysUsrQueryApiService.searchSysUsrSysRList(condition));
			if(usrList != null && usrList.size()>0){
				vo.setCertNo(usrList.get(0).getCertNo().replaceAll("(\\d{4})\\d{10}(\\w{4})","$1********$2"));
				//vo.setRefMp(usrList.get(0).getUsrNm().replaceAll("(\\d{3})\\d{4}(\\d{4})","$1****$2"));
				vo.setRefMp(usrList.get(0).getUsrNm());
				vo.setCustName(usrList.get(0).getRlNm());
			}
			//获取领取人信息
			if(!StringUtils.isEmpty(vo.getClaim())){
				condition.setUsrId(Long.valueOf(vo.getClaim()));
				List<SysUsrSysRVO> usrClaimList = SysUsrSysRVOTransform.toVOList(sysUsrQueryApiService.searchSysUsrSysRList(condition));
				if(usrClaimList != null && usrClaimList.size()>0){
					vo.setClaimNm(usrClaimList.get(0).getRlNm());
				}
			}
		}
		setDictData(voList);
		resultPage.setResultList(voList);
		return resultPage;
	}

	@Override
	public boolean cancel(McrCstCreditRecVO entity) throws BaseException {
		if(null == entity){
			BaseLogUtils.info(logger, "cancel", "作废对象参数不能为空!", CurrentThreadContext.getCurrentUserName());
			return false;
		}
		return publicMcrCstCreditRecApiService.cancelMcrCstCreditRecDTO(entity.getId());
	}

	@Override
	public List<McrCstCreditRecVO> searchList(McrCstCreditRecQC qc)throws BaseException {
		if(null == qc){
			BaseLogUtils.info(logger, "cancel", "作废对象参数不能为空!", CurrentThreadContext.getCurrentUserName());
			qc = new McrCstCreditRecQC();
		}
		 List<McrCstCreditRecVO> list =McrCstCreditRecVOTransform.toVOList(publicMcrCstCreditRecApiService.searchMcrCstCreditRecDTOList(qc));
		 return list;
	}

	@Override
	public Long addAudReturnVisit(McrVisitVO entity, Integer auditVisitStatus) throws BaseException {
        if (null == entity || null == auditVisitStatus){
			BaseLogUtils.info(logger,"addAudReturnVisit","添加小贷信审授信.参数或者状态不能为空：projectId:"+entity.getProjectId()+",states:"+auditVisitStatus);
			throw new BaseException(BaseExceptionConstant.COMMON_0002,"添加数据异常");
		}

		BaseLogUtils.info(logger,"addAudReturnVisit","添加小贷信审授信.开始添加小贷授信：projectId:"+entity.getProjectId()+",states:"+auditVisitStatus);

        Long id = 0L;
		try {
			if(StringUtils.isEmpty(entity.getCarType())){
				BaseLogUtils.info(logger,"addAudReturnVisit","添加小贷信审授信.车型不能为空：projectId:"+entity.getProjectId()+",states:"+auditVisitStatus);
				throw new BaseException(BaseExceptionConstant.COMMON_0002,"车型不能为空");
			}

			// 存储授信记录
			id = addMcrVisitInfo(entity);
			if (McrCstCreditRecConstant.STATUS5.equals(auditVisitStatus)){
                BaseLogUtils.info(logger,"addAudReturnVisit","添加小贷信审授信.该订单为保存订单：projectId:"+entity.getProjectId()+",states:"+auditVisitStatus);
			    return id;
            }

			// 逻辑迁移到public-loan-service
			cn.lionbridgecapital.loan.model.vo.McrVisitVO mcrVisitVO = new cn.lionbridgecapital.loan.model.vo.McrVisitVO();
			BeanUtils.copyProperties(entity, mcrVisitVO);
			mcrOutCommApiService.quotaNode(mcrVisitVO, id, auditVisitStatus, CurrentThreadContext.getCurrentUserId());
		}catch (BaseException ex){
			BaseLogUtils.error(logger, "addAudReturnVisit", "添加授信记录.异常.DATA:" + JSONObject.toJSONString(entity) +",ex:"+ex.getMessage(),ex);
		}catch (Exception ex) {
			BaseLogUtils.error(logger, "addAudReturnVisit", "添加授信记录.异常.DATA:" + JSONObject.toJSONString(entity) +",ex:"+ex.getMessage(),ex);
		}
		return id;
	}

	/**
	 * 新增信审信息
	 * @param entity
	 * @return
	 */
	private Long addMcrVisitInfo(McrVisitVO entity){
		BaseLogUtils.info(logger,"addMcrVisitInfo","开始新增参数，projectId:"+entity.getProjectId());
		Long visitId = null;

		Long projectId = entity.getProjectId();
		McrVisitProposerDTO mcrVisitProposerDTO = entity.getMcrVisitProposerDTO();
		McrVisitDriverDTO mcrVisitDriverDTO = entity.getMcrVisitDriverDTO();
		McrVisitCarDTO mcrVisitCarDTO = entity.getMcrVisitCarDTO();
		McrVisitCarBusDTO mcrVisitCarBusDTO = entity.getMcrVisitCarBusDTO();

		try{
			// 申请人信息
			BaseLogUtils.info(logger,"addMcrVisitInfo","新增信审.开始获取申请人信息：projectId:"+entity.getProjectId());
			McrVisitProposerQC mcrVisitProposerQC = new McrVisitProposerQC();
			mcrVisitProposerQC.setProjectId(projectId);
			mcrVisitProposerQC.setIsDel(BaseConstant.IS_YESNO_NO);
			List<McrVisitProposerDTO> visitProposer = this.mcrOutLoanApiService.getVisitProposer(mcrVisitProposerQC);

			// 驾驶证信息
			BaseLogUtils.info(logger,"addMcrVisitInfo","新增信审.开始获取驾驶证信息：projectId:"+entity.getProjectId());
			McrVisitDriverQC mcrVisitDriverQC = new McrVisitDriverQC();
			mcrVisitDriverQC.setProjectId(projectId);
			mcrVisitDriverQC.setIsDel(BaseConstant.IS_YESNO_NO);
			List<McrVisitDriverDTO> visitDriver = this.mcrOutLoanApiService.getVisitDriver(mcrVisitDriverQC);

			// 车辆信息
			BaseLogUtils.info(logger,"addMcrVisitInfo","新增信审.开始获取车辆信息：projectId:"+entity.getProjectId());
			McrVisitCarQC mcrVisitCarQC = new McrVisitCarQC();
			mcrVisitCarQC.setProjectId(projectId);
			mcrVisitCarQC.setIsDel(BaseConstant.IS_YESNO_NO);
			List<McrVisitCarDTO> visitCar = this.mcrOutLoanApiService.getVisitCar(mcrVisitCarQC);

			// 车辆运营信息
			BaseLogUtils.info(logger,"addMcrVisitInfo","新增信审.开始获取车辆运营信息：projectId:"+entity.getProjectId());
			McrVisitCarBusQC mcrVisitCarBusQC = new McrVisitCarBusQC();
			mcrVisitCarBusQC.setProjectId(projectId);
			mcrVisitCarBusQC.setIsDel(BaseConstant.IS_YESNO_NO);
			List<McrVisitCarBusDTO> visitCarBus = this.mcrOutLoanApiService.getVisitCarBus(mcrVisitCarBusQC);

			// 修改、新增申请人信息
			if (CollectionUtils.isNotEmpty(visitProposer)){
				McrVisitProposerDTO mcrVisitProposerDTO1 = visitProposer.get(0);
				mcrVisitProposerDTO.setId(mcrVisitProposerDTO1.getId());
				mcrVisitProposerDTO.setMdfTm(new Date());
				BaseLogUtils.info(logger,"addMcrVisitInfo","新增信审.修改申请人授信：projectId:"+entity.getProjectId()+",visitProposer:"+JSONObject.toJSONString(mcrVisitProposerDTO));
				boolean proposer = this.mcrOutLoanApiService.modifyVisitProposer(mcrVisitProposerDTO);
				BaseLogUtils.info(logger,"addMcrVisitInfo","新增信审.修改申请人授信结束：projectId:"+entity.getProjectId()+",结果："+proposer);
				visitId = mcrVisitProposerDTO1.getId();
			}else {
				mcrVisitProposerDTO.setCrtTm(new Date());
				BaseLogUtils.info(logger,"addMcrVisitInfo","新增信审.新增申请人授信开始：projectId:"+entity.getProjectId()+",visitProposer:"+JSONObject.toJSONString(mcrVisitProposerDTO));
				visitId = this.mcrOutLoanApiService.addVisitProposer(mcrVisitProposerDTO);
				BaseLogUtils.info(logger,"addMcrVisitInfo","新增信审.新增申请人授信结束：projectId:"+entity.getProjectId()+",结果："+visitId);
			}

			// 修改、新增驾驶证信息
			if (CollectionUtils.isNotEmpty(visitDriver)){
				McrVisitDriverDTO mcrVisitDriverDTO1 = visitDriver.get(0);
				mcrVisitDriverDTO.setId(mcrVisitDriverDTO1.getId());
				mcrVisitDriverDTO.setMdfTm(new Date());
				BaseLogUtils.info(logger,"addMcrVisitInfo","新增信审.修改驾驶证授信开始：projectId:"+entity.getProjectId()+"," +
						"visitDriverDTO:"+JSONObject.toJSONString(mcrVisitDriverDTO));
				boolean driver = this.mcrOutLoanApiService.modifyVisitDriver(mcrVisitDriverDTO);
				BaseLogUtils.info(logger,"addMcrVisitInfo","新增信审.修改驾驶证授信结束：projectId:"+entity.getProjectId()+",结果："+driver);
			}else {
				mcrVisitDriverDTO.setCrtTm(new Date());
				BaseLogUtils.info(logger,"addMcrVisitInfo","新增信审.新增驾驶证授信开始：projectId:"+entity.getProjectId()+"," +
						"visitDriver:"+JSONObject.toJSONString(mcrVisitDriverDTO));
				Long aLong1 = this.mcrOutLoanApiService.addVisitDriver(mcrVisitDriverDTO);
				BaseLogUtils.info(logger,"addMcrVisitInfo","新增信审.新增驾驶证授信结束：projectId:"+entity.getProjectId()+",结果："+aLong1);
			}

			// 修改、新增车辆信息
			if (CollectionUtils.isNotEmpty(visitCar)){
				McrVisitCarDTO mcrVisitCarDTO1 = visitCar.get(0);
				mcrVisitCarDTO.setId(mcrVisitCarDTO1.getId());
				mcrVisitCarDTO.setMdfTm(new Date());
				BaseLogUtils.info(logger,"addMcrVisitInfo","新增信审.修改车辆授信开始：projectId:"+entity.getProjectId()+",visitCarDTO:"+mcrVisitCarDTO);
				boolean car = this.mcrOutLoanApiService.modifyVisitCar(mcrVisitCarDTO);
				BaseLogUtils.info(logger,"addMcrVisitInfo","新增信审.修改车辆授信结束：projectId:"+entity.getProjectId()+",结果："+car);
			}else {
				mcrVisitCarDTO.setCrtTm(new Date());
				BaseLogUtils.info(logger,"addMcrVisitInfo","新增信审.新增车辆信息授信开始：projectId:"+entity.getProjectId()+",visitCarDTO:"+mcrVisitCarDTO);
				Long aLong2 = this.mcrOutLoanApiService.addVisitCar(mcrVisitCarDTO);
				BaseLogUtils.info(logger,"addMcrVisitInfo","新增信审.新增车辆信息授信结束：projectId:"+entity.getProjectId()+",结果："+aLong2);
			}

			// 修改、新增车辆运营信息
			if (CollectionUtils.isNotEmpty(visitCarBus)){
				McrVisitCarBusDTO mcrVisitCarBusDTO1 = visitCarBus.get(0);
				mcrVisitCarBusDTO.setId(mcrVisitCarBusDTO1.getId());
				mcrVisitCarBusDTO.setMdfTm(new Date());
				BaseLogUtils.info(logger,"addMcrVisitInfo","新增信审.修改车辆运营授信开始：projectId:"+entity.getProjectId()+",visitCarBus:"+mcrVisitCarBusDTO);
				boolean carBus = this.mcrOutLoanApiService.modifyVisitCarBus(mcrVisitCarBusDTO);
				BaseLogUtils.info(logger,"addMcrVisitInfo","新增信审.修改车辆运营授信结束：projectId:"+entity.getProjectId()+",结果："+carBus);
			}else {
				mcrVisitCarBusDTO.setCrtTm(new Date());
				BaseLogUtils.info(logger,"addMcrVisitInfo","新增信审.新增车辆运营信息授信开始：projectId:"+entity.getProjectId()+",visitCarBus:"+mcrVisitCarBusDTO);
				Long aLong3 = this.mcrOutLoanApiService.addVisitCarBus(mcrVisitCarBusDTO);
				BaseLogUtils.info(logger,"addMcrVisitInfo","新增信审.新增车辆运营信息授信结束：projectId:"+entity.getProjectId()+",结果："+aLong3);
			}
		}catch (BaseException ex){
			BaseLogUtils.error(logger,"addMcrVisitInfo","新增信审.异常：projectId:"+entity.getProjectId()+",ex:"+ex.getMessage(),ex);
			throw new BaseException(BaseExceptionConstant.COMMON_0002,"新增信审授信数据异常");
		}catch (Exception ex){
			BaseLogUtils.error(logger,"addMcrVisitInfo","新增信审.异常：projectId:"+entity.getProjectId()+",ex:"+ex.getMessage(),ex);
			throw new BaseException(BaseExceptionConstant.COMMON_0002,"新增信审授信数据异常");
		}
		return visitId;
	}

	/**
     * 添加数据字典名称
     * @param voList
     */
	public void setDictData(List<McrCstCreditRecVO> voList){
        if(CollectionUtils.isEmpty(voList)) return;
        Map<String, String> creditStatusMap = this.sysDictionaryApiService.searchGroupToMap(CurrentThreadContext.getCurrentSysCd(), CurrentThreadContext.getCurrentOrgCd(), McrCstCreditRecConstant.CREDIT_STATUS);
        Map<String, String> auditVisitStatusMap = this.sysDictionaryApiService.searchGroupToMap(CurrentThreadContext.getCurrentSysCd(), CurrentThreadContext.getCurrentOrgCd(), McrCstCreditRecConstant.AUDIT_VISIT_STATUS);
        for(McrCstCreditRecVO vo:voList){
        	if(vo.getCreditStatus() != null){
        		vo.setCreditNm(creditStatusMap.get(vo.getCreditStatus().toString()));
        	}
            if(vo.getAuditVisitStatus() != null){
            	vo.setAuditVisitNm(auditVisitStatusMap.get(vo.getAuditVisitStatus().toString()));
            }  
        }
    }
	@Override
	public DataResultDTO test() throws BaseException {
		return publicMcrCstCreditRecApiService.JudgeHeavyLight("LZZ1ELSDXHD240071");
		//return mcrCstCreditRecApiService.getVehicleMileage("津C20053");
		//return mcrCstCreditRecApiService.judgeIsBlack("181102918000190");
	}
}
